# tool macros
CC := sdcc
CCFLAGS :=
DBGFLAGS := -g
CCOBJFLAGS := $(CCFLAGS) -c

# path macros
CURR_PATH := .
BINN_PATH := $(CURR_PATH)/bin
OBJ_PATH := $(CURR_PATH)/obj
SRC_PATH := $(CURR_PATH)/src
DBG_PATH := $(CURR_PATH)/debug

# compile macros
TARGET_NAME := main
#ifeq ($(OS),Windows_NT)
#	TARGET_NAME := $(addsuffix .exe,$(TARGET_NAME))
#endif
TARGET := $(BINN_PATH)/$(TARGET_NAME).bin
TARGET_HEX := $(BINN_PATH)/$(TARGET_NAME).hex
TARGET_IHX := $(BINN_PATH)/$(TARGET_NAME).ihx
TARGET_DEBUG := $(DBG_PATH)/$(TARGET_NAME)

# src files & obj files
SRC := $(foreach x, $(SRC_PATH), $(wildcard $(addprefix $(x)/*,.c*)))
OBJ := $(addprefix $(OBJ_PATH)/, $(addsuffix .rel, $(notdir $(basename $(SRC)))))
OBJ_DEBUG := $(addprefix $(DBG_PATH)/, $(addsuffix .rel, $(notdir $(basename $(SRC)))))

# clean files list
DISTCLEAN_LIST := $(OBJ) \
                  $(OBJ_DEBUG)
CLEAN_LIST := $(TARGET) \
			  $(TARGET_DEBUG) \
			  $(DISTCLEAN_LIST)

# default rule
default: makedir all

# non-phony targets

$(TARGET) : $(TARGET_HEX)
	@objcopy -I ihex -O binary $< $@
	@echo "5-  bin Compile done."

$(TARGET_HEX) : $(TARGET_IHX)
	@packihx $< > $@
	@echo "4-  hex Compile done."

$(TARGET_IHX): $(OBJ)
	$(CC) $(CCFLAGS) -o $@ $(OBJ)
	@echo "3-  ihx Compile done."

$(OBJ_PATH)/%.rel: $(SRC_PATH)/%.c*
	$(CC) $(CCOBJFLAGS) $< -o $@

$(DBG_PATH)/%.rel: $(SRC_PATH)/%.c*
	$(CC) $(CCOBJFLAGS) $(DBGFLAGS) $< -o $@

$(TARGET_DEBUG): $(OBJ_DEBUG)
	$(CC) $(CCFLAGS) $(DBGFLAGS) $(OBJ_DEBUG) -o $@

# phony rules
.PHONY: makedir
makedir:
	@mkdir -p $(BINN_PATH) $(OBJ_PATH) $(DBG_PATH)

.PHONY: all
all: $(TARGET)

.PHONY: debug
debug: $(TARGET_DEBUG)

.PHONY: clean
clean:
	@echo CLEAN $(CLEAN_LIST)
	@rm -f $(CLEAN_LIST)

.PHONY: distclean
distclean:
	@echo CLEAN $(CLEAN_LIST)
	@rm -f $(DISTCLEAN_LIST)